from datetime import datetime
from typing import Optional, List
from pydantic import BaseModel, Field, validator
from decimal import Decimal

class BillBase(BaseModel):
    type: str = Field(..., description="账单类型: income/expense")
    amount: Decimal = Field(..., description="金额")
    category: str = Field(..., description="分类")
    date: datetime = Field(..., description="日期")
    remark: Optional[str] = Field(None, description="备注")

    @validator('date', pre=True)
    def parse_date(cls, v):
        if isinstance(v, str):
            try:
                return datetime.strptime(v, "%Y-%m-%d")
            except ValueError:
                raise ValueError("Invalid date format. Use YYYY-MM-DD")
        return v

class BillCreate(BillBase):
    pass

class BillUpdate(BillBase):
    type: Optional[str] = None
    amount: Optional[Decimal] = None
    category: Optional[str] = None
    date: Optional[datetime] = None

class BillInDB(BillBase):
    id: int
    user_id: int
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True

class Bill(BillBase):
    id: int
    user_id: int
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True

class BillList(BaseModel):
    total: int
    list: List[Bill]

class CategoryStats(BaseModel):
    category: str
    total: float
    percent: float

class BillStats(BaseModel):
    overview: List[dict]
    categories: dict 